package metalink;

import java.util.ArrayList;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import vo.LoginInfoVo;

import model.LoginMo;
import myutil.Connect;

import com.opensymphony.xwork2.ActionSupport;

public class Login extends ActionSupport {
	String username;
	String password;
	String site;
	HttpSession sessioncheck;
	HttpSession session;
	ArrayList<LoginInfoVo> details = new ArrayList<LoginInfoVo>();

	public String execute() {
		sessioncheck = ServletActionContext.getRequest().getSession();
		if (null != sessioncheck.getAttribute("login_true")) {
			if(sessioncheck.getAttribute("user_type").equals("admin"))
			{
				return "admin";
			}
			if(sessioncheck.getAttribute("user_type").equals("student"))
			{
				return "student";
			}
			if(sessioncheck.getAttribute("user_type").equals("staff"))
			{
				return "staff";
			}
			
		}
		if (username == null || password == null || site == null) {
			return ERROR;
		}
		LoginMo loginMo = new LoginMo();
		LoginInfoVo loginInfo = new LoginInfoVo();
		try {
			details = loginMo.authenticate(username, password, site);
			session = ServletActionContext.getRequest().getSession();
			if (details.size()!=0) {

				session.setAttribute("username", username);
				session.setAttribute("login_true", "yes");
				session.setMaxInactiveInterval(30 * 60);
				String userType = details.get(0).getUser_type();
				session.setAttribute("user_type", userType);
				System.out.println("user id is : "+details.get(0).getUser_id());
				session.setAttribute("user_id", details.get(0).getUser_id());
				if(userType.equals("admin"))
				{	
					return "admin";
				}
				else if(userType.equals("student"))
				{
					return "student";
				}
				else if(userType.equals("staff"))
				{
					return "staff";
				}
			} else {
				throw new Exception();
				
			}

		} catch (Exception e) {
			addActionError("Invalid Site Id or Username or password.Please try again");
			session = ServletActionContext.getRequest().getSession();
			session.invalidate();
			return ERROR;
		}
		return ERROR;

	}

	public ArrayList<LoginInfoVo> getDetails() {
		return details;
	}

	public void setDetails(ArrayList<LoginInfoVo> details) {
		this.details = details;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getSite() {
		return site;
	}

	public void setSite(String site) {
		this.site = site;
	}
}
